<template>
    <div id="absenceChart" :style="{ width: props.width, height: props.height }"></div>
</template>

<script setup lang="ts">
import { GetStatistics } from '@/controllers/auditController';
import { message } from '@/utils/message';
import * as echarts from 'echarts';
import { onMounted, ref } from 'vue';

const props = defineProps<{ width: string, height: string }>();
const chartData = ref<any[]>([]);

onMounted(async () => {
    try {
        await getStatistics();
        drawChart();
    } catch (error) {
        console.error(error);
    }
});

async function getStatistics() {
    try {
        const data = await GetStatistics();
        chartData.value = data;
    } catch (error: any) {
        message(error.message, 'error');
    }
}

async function drawChart() {
    const c = document.getElementById('absenceChart');
    if (!c) {
        console.error('元素不存在！');
        return;
    }
    const chart = echarts.init(c);

    const option: echarts.EChartsOption = {
        title: {
            text: '学期请假次数统计',
            subtext: '2023-2024-2',
            left: 'center'
        },
        tooltip: {
            trigger: 'item'
        },
        legend: {
            orient: 'vertical',
            left: 'left'
        },
        series: [
            {
                name: '请假',
                type: 'pie',
                radius: '50%',
                data: chartData.value.map(item => ({
                    value: item.value,
                    name: item.name
                })),
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };
    option && chart.setOption(option);
}
</script>
